<?php

namespace app\common\business;

use app\common\lib\Str;
use think\Exception;
use think\facade\Filesystem;

class File
{
    public function uploadFile($file): string
    {
        if(!$this->checkFile($file->getOriginalName(),'image')){
            throw new Exception('上传的格式不允许');
        }
        $filePath=Filesystem::disk('public')->putFile('uploads',$file);
        $domain = Str::globalRequestDomain();
        $url=$domain.'/'.str_replace(DIRECTORY_SEPARATOR,'/',$filePath);
        $model=new \app\common\model\mysql\File();
        $model->save(['url'=>$url]);
        return $url;
    }

    public function getFileList($page,$limit){
        $model=new \app\common\model\mysql\File();
        return $model->getTableList([],$page,$limit);
    }
    private static $fileAllow=[
        'image'=>['png','jpg','jpeg','bmp','gif','webp','heif']
    ];

    public function checkFile($name,$type='image'): bool
    {
        $ext=explode('.',$name);
        $ext=end($ext);
        $ext=strtolower($ext);
        if(!in_array($ext,self::$fileAllow[$type])){
            return false;
        }
        return true;
    }
}
